<template>
	<view>
		<view class="address-wrapper" @click="getAddr">
			<view class="address" v-if="addr.userName">
				<view class="receiver">
					<view class="name">收货人：{{ addr.userName }}</view>
					<view class="phone-num">{{ addr.telNumber }}</view>
					<text class="iconfont icon-arrow-right"></text>
				</view>
				<view class="address-txt">收货地址：{{ addr.provinceName + addr.cityName + addr.countyName + addr.detailInfo }}</view>
			</view>
			<!-- 选择地址 -->
			<view class="choose-address">
				<view>请选择地址</view>
				<text class="iconfont icon-arrow-right"></text>
			</view>
			<view class="flower"><image src="/static/images/cart_border@2x.png"></image></view>
		</view>

		<!-- 商品列表 -->
		<view class="goods-list">
			<view class="goods-item" v-for="(item, index) in goodsList" :key="index">
				<image :src="item.goods_small_logo" alt="" />
				<view class="right">
					<text class="text-line2">{{ item.goods_name }}</text>
					<view class="btm">
						<text class="price">
							￥
							<text>{{ item.goods_price }}</text>
							.00
						</text>
						<view class="goods-num">
							<text>{{ item.num }}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<view class="bottom-fixed" @click="wxPay">微信支付({{ totalPrice }}.00)</view>
	</view>
</template>

<script>
const ADDR_KEY = 'addr';
const CART_KEY = 'cart';

export default {
	data() {
		return {
			// 地址
			addr: uni.getStorageSync(ADDR_KEY) || {},
			// 商品列表
			goodsList: []
		};
	},
	computed: {
		// 总价格
		totalPrice() {
			return this.goodsList.reduce((sum, item) => {
				return sum + item.num * item.goods_price;
			}, 0);
		}
	},
	onLoad(options) {
		this.goodsId = parseInt(options.goodsId);
		this.storageCartArr = this.$store.state.cart
		// 发请求了
		this.queryGoodsList();
	},
	methods: {
		wxPay() {
			//TODO,判断商品数量
			if (!this.addr.userName) {
				uni.showToast({
					title: '请选择收货地址',
					icon: 'none'
				});
				return;
			}
			// 创建订单
			this.createOrder();
		},
		// 创建订单
		async createOrder() {
			let data = await this.$request({
				url: '/api/public/v1/my/orders/create',
				isAuth: true,
				method: 'POST',
				data: {
					order_price: this.totalPrice,
					// getConsigneeAddr的计算结果的确是也是依赖this.addr,但是返回值并没有在结构中使用
					consignee_addr: this.getConsigneeAddr(),
					goods: this.getGoodsArr()
				}
			});
			this.orderNumber = data.order_number;
			//获取支付参数,并唤起微信支付
			this.doPay();
			// 订单创建成功，无论支付成功还是失败，都把storage cart里面勾选的商品去掉
			// 如果不是从立即购买跳转,才去掉storage cart勾选的商品
			!this.goodsId && this.arrangeStorageCart();
		},
		// storage cart里面勾选的商品去掉
		arrangeStorageCart() {
			this.$store.commit('arrangeCart')
		},
		// 获取支付参数,并唤起微信支付
		async doPay() {
			let token = uni.getStorageSync('token');

			let data = await this.$request({
				url: '/api/public/v1/my/orders/req_unifiedorder',
				// header: {
				// 	Authorization: token
				// },
				isAuth: true,
				method: 'POST',
				data: {
					order_number: this.orderNumber
				}
			});
			console.log(data);

			// 唤起微信支付
			uni.requestPayment({
				...data.pay,
				success: res => {
					uni.showToast({
						title: '成功',
						icon: 'none'
					});
					uni.navigateTo({
						url: '/pages/order_result/order_result'
					});
				},
				fail: err => {
					uni.showToast({
						title: '失败',
						icon: 'none'
					});
					uni.navigateTo({
						url: '/pages/order_result/order_result?orderNumber=' + this.orderNumber
					});
				}
			});
		},
		getGoodsArr() {
			return this.goodsList.map(item => {
				return {
					goods_id: item.goods_id,
					goods_number: item.num,
					goods_price: item.goods_price
				};
			});
		},
		getConsigneeAddr() {
			let { provinceName, cityName, countyName, detailInfo, userName, telNumber } = this.addr;
			return `${provinceName}${cityName}${countyName}${detailInfo} ${userName} ${telNumber}`;
		},
		// 获取购物车商品列表
		async queryGoodsList() {
			//取storage cart里面每一项goodsId以,拼接
			// let idStr = ''
			// storageCartArr.forEach(item=>{
			// 	idStr+=item.goodsId+','
			// })
			// console.log(idStr)
			//构造goodsId数组，然后join
			// 立即购买
			if (this.goodsId) {
				// 构造一个storageCart
				this.storageCartArr = [
					{
						goodsId: this.goodsId,
						checked: true,
						num: 1
					}
				];
			}
			//只取storage cart里面勾选的商品
			this.storageCartArr = this.storageCartArr.filter(item => {
				return item.checked;
			});
			let goodsIdArr = this.storageCartArr.map(item => {
				return item.goodsId;
			});

			let idStr = goodsIdArr.join(',');

			let _goodsList = await this.$request({
				url: '/api/public/v1/goods/goodslist?goods_ids=' + idStr
			});
			// storageCartArr和_goodsList合并,以storageCartArr为主
			this.goodsList = this.storageCartArr.map(storageGoods => {
				// storageGoods.goodsId去_goodsList里面找一项goods_id相等那一项, storageGoods和找到的对象进行合并
				let targetGoods = _goodsList.find(item => {
					return item.goods_id === storageGoods.goodsId;
				});
				// 注意点,这里是对象
				return { ...storageGoods, ...targetGoods };
			});
		},
		// 授权获取通讯地址
		getAddr() {
			uni.authorize({
				scope: 'scope.address',
				success: () => {
					uni.chooseAddress({
						// 注意这里使用箭头函数
						success: res => {
							this.addr = res;
							uni.setStorageSync(ADDR_KEY, res);
						}
					});
				},
				fail: () => {
					//先提示，然后设置里面允许
					uni.showModal({
						title: '提示',
						content: '请在打开的设置里面允许通讯地址',
						success: res => {
							if (res.confirm) {
								// 打开授权设置弹框
								uni.openSetting();
							}
						}
					});
				}
			});
		}
	}
};
</script>

<style lang="less">
.address-wrapper {
	background-color: #fff;
}

.address {
	display: flex;
	flex-direction: column;
	padding: 44rpx 30rpx 48rpx 20rpx;
	.receiver {
		display: flex;
		justify-content: space-between;
		margin-bottom: 50rpx;
		position: relative;
		.phone-num {
			margin-right: 40rpx;
		}
		.icon-arrow-right {
			position: absolute;
			top: 8rpx;
			right: 0;
			color: #999;
		}
	}
}

.choose-address {
	display: flex;
	padding: 44rpx 30rpx 48rpx 20rpx;
	justify-content: space-between;
	.icon-arrow-right {
		color: #999;
	}
}

.flower {
	image {
		height: 16rpx;
		width: 100%;
		display: block;
	}
}

.goods-item {
	height: 206rpx;
	background-color: #fff;
	border-top: 1rpx solid #ddd;
	display: flex;
	box-sizing: border-box;
	align-items: center;
	image {
		width: 160rpx;
		height: 160rpx;
		margin-left: 30rpx;
	}
	.right {
		flex: 1;
		display: flex;
		flex-direction: column;
		margin: 0 20rpx 0 18rpx;
		.btm {
			display: flex;
			margin-top: 40rpx;
			justify-content: space-between;
			.price {
				color: #eb4450;
				> text {
					font-size: 24px;
				}
			}
			.goods-num {
				display: flex;
				align-items: center;
				button {
					width: 60rpx;
					height: 50rpx;
					box-sizing: border-box;
					display: flex;
					justify-content: center;
					align-items: center;
					border: 4rpx solid #666;
				}
				text {
					margin: 0 30rpx;
				}
			}
		}
	}
}
.goods-list {
	position: absolute;
	bottom: 98rpx;
	top: 243rpx;
	width: 100%;
	overflow: auto;
	padding-bottom: 60rpx;
	background-color: #f4f4f4;
}

.bottom-fixed {
	position: absolute;
	height: 98rpx;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: #1aad19;
	color: #fff;
	line-height: 98rpx;
	text-align: center;
}
</style>
